package vip.meeet.concurrent;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadId {
         // Atomic integer containing the next thread ID to be assigned
         private static final AtomicInteger nextId = new AtomicInteger(0);
    
         // Thread local variable containing each thread's ID
         private static final ThreadLocal<Integer> threadId =
             new ThreadLocal<Integer>() {
                 @Override
                 protected Integer initialValue() {
                     return nextId.getAndIncrement();
             }
         };
    
         // Returns the current thread's unique ID, assigning it if necessary
         public static int get() {
             return threadId.get();
         }
         
         public static void main(String[] args) {
            ExecutorService pool = Executors.newFixedThreadPool(10);
            for(int i=0;i<10;i++){
                Future<Integer> future = pool.submit(new GetId());
                boolean done = future.isDone();
                while(!done){
                    done = future.isDone();
                }
                try {
                    System.out.println(future.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                
            }
            
        }
        static class GetId implements Callable<Integer>{

            @Override
            public Integer call() throws Exception {
                return ThreadId.get();
            }
            
        }
}